#include "sqliteoperator.h"


// 构造函数中初始化文件名为 dbName 数据库对象，并建立数据库
SqliteOperator::SqliteOperator(const QString &dbName)
{
    if (QSqlDatabase::contains("qt_sql_default_connection"))
    {
        database = QSqlDatabase::database("qt_sql_default_connection");
    }
    else
    {
        // 建立和SQlite数据库的连接
        database = QSqlDatabase::addDatabase("QSQLITE");
        // 设置数据库文件的名字
        database.setDatabaseName(dbName);
    }
}


// 打开数据库
bool SqliteOperator::openDb()
{
    if (!database.open())
    {
        qDebug() << "Error: Failed to connect database." << database.lastError();
        return false;
    }

    return true;
}

// 创建数据表
bool SqliteOperator::createTable(const QString &tableName, const QString &tableSql)
{
    QSqlQuery sqlQuery;
    QString createSql;

    // 若表不存在则创建
    if (!isTableExist(tableName))
    {
        createSql = QString("CREATE TABLE ").append(tableName);
        createSql.append("(");
        createSql.append(tableSql);
        createSql.append(")");

        sqlQuery.prepare(createSql);
        if (!sqlQuery.exec())
        {
            qDebug() << "Error: Fail to create table. " << sqlQuery.lastError();
            qDebug() << "createSql:" << createSql << endl;
            return false;
        }

        qDebug() << "Table created!";
    }

    return true;
}

// 判断数据库中某个数据表是否存在
bool SqliteOperator::isTableExist(const QString &tableName)
{
    QSqlDatabase database = QSqlDatabase::database();
    if (database.tables().contains(tableName))
    {
        return true;
    }

    return false;
}

//删除数据表
bool SqliteOperator::deleteTable(const QString &tableName)
{
    QSqlQuery sqlQuery;

    sqlQuery.exec(QString("DROP TABLE %1").arg(tableName));
    if (sqlQuery.exec())
    {
        qDebug() << sqlQuery.lastError();
        return false;
    }
    else
    {
        qDebug() << "deleted table[" << tableName << "] success";
    }

    return true;
}

bool SqliteOperator::cleanTable(const QString &tableName)
{
    QSqlQuery sqlQuery;

    sqlQuery.exec(QString("DELETE FROM %1").arg(tableName));
    if (sqlQuery.exec())
    {
        qDebug() << sqlQuery.lastError();
        return false;
    }
    else
    {
        qDebug() << "clean table[" << tableName << "] success";
    }

    return true;
}

void SqliteOperator::closeDb(void)
{
    database.close();
}
